// 路径：src/main/java/electricity/service/DocumentService.java
package electricity.service.impl;

import electricity.Utils.AliOssUtil;
import electricity.domain.DirectoryNode;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DocumentService {

    private final


    AliOssUtil ossUtil;
    private final String bucketName;

    // 注入 OSS 工具类和存储空间名称
    public DocumentService(AliOssUtil ossUtil,
                           @Value("${aliyun.oss.bucketName}") String bucketName) {
        this.ossUtil = ossUtil;
        this.bucketName = bucketName;
    }

    /**
     * 动态从 OSS 生成目录树
     */
    public List<DirectoryNode> getDirectoryTree() {
        List<String> allFilePaths = ossUtil.listAllObjectPaths(bucketName);

        Set<String> folderPaths = new HashSet<>();
        for (String filePath : allFilePaths) {
            // 提取所有可能的目录（包括空目录和子目录）
            int lastSlash = filePath.lastIndexOf("/");
            if (lastSlash >= 0) {
                // 情况1：文件在子目录（如 "city/xxx.docx" -> "city"）
                String folder = filePath.substring(0, lastSlash);
                folderPaths.add(folder);
                addParentFolders(folder, folderPaths);
            } else {
                // 情况2：文件在根目录（如 "xxx.docx" -> 根目录 ""）
                folderPaths.add("");
            }
        }

        // 手动添加空目录（如 "city/" 本身）
        for (String filePath : allFilePaths) {
            if (filePath.endsWith("/")) { // 如果 OSS 中有空目录对象（如手动创建的文件夹）
                folderPaths.add(filePath);
            }
        }

        return buildDirectoryTree("", folderPaths);
    }

    /**
     * 递归添加父文件夹（例如 "a/b/c" -> 添加 "a"、"a/b"、"a/b/c"）
     */
    private void addParentFolders(String folderPath, Set<String> folderPaths) {
        if (folderPath.contains("/")) {
            String parent = folderPath.substring(0, folderPath.lastIndexOf("/"));
            folderPaths.add(parent);
            addParentFolders(parent, folderPaths);
        }
    }

    /**
     * 递归构建目录树
     */
    // DocumentService.java
    private List<DirectoryNode> buildDirectoryTree(String parentPath, Set<String> allFolders) {
        List<String> childFolders = allFolders.stream()
                .filter(path -> path.startsWith(parentPath)
                        && !path.equals(parentPath)
                        && path.substring(parentPath.isEmpty() ? 0 : parentPath.length()).split("/").length == 1)
                .collect(Collectors.toList());

        List<DirectoryNode> children = new ArrayList<>();
        for (String childPath : childFolders) {
            String childName = childPath; // 直接用路径作为名称（如 "city"）
            if (!parentPath.isEmpty()) {
                childName = childPath.substring(parentPath.length() + 1);
            }

            // 处理空目录名称（如 "city/" -> "city"）
            if (childName.endsWith("/")) {
                childName = childName.substring(0, childName.length() - 1);
            }

            DirectoryNode node = new DirectoryNode(
                    (long) childPath.hashCode(),
                    childName,
                    childPath
            );
            node.setChildren(buildDirectoryTree(childPath, allFolders));
            children.add(node);
        }

        children.sort(Comparator.comparing(DirectoryNode::getName));
        return children;
    }

    /**
     * 获取指定目录下的文件列表
     */
    public List<AliOssUtil.OssFile> getFilesInDirectory(String directory) {
        return ossUtil.listFilesInDirectory(bucketName, directory);
    }

    /**
     * 上传文件到指定目录
     */
    public String uploadFileToDirectory(MultipartFile file, String directory) throws IOException {
        return ossUtil.uploadFile(
                file.getInputStream(),
                bucketName,
                directory,
                file.getOriginalFilename()
        );
    }
}
